package com.lzw.breezeNovel.WebAdmin.service.impl;



import com.lzw.breezeNovel.WebAdmin.mapper.BookMapper;
import com.lzw.breezeNovel.WebAdmin.mapper.ChapterMapper;
import com.lzw.breezeNovel.WebAdmin.service.BookService;
import com.lzw.breezeNovel.WebAdmin.vo.BookVo;
import com.lzw.breezeNovel.WebAdmin.vo.StatisticsVo;
import com.lzw.breezeNovel.common.exception.BaseException;
import com.lzw.breezeNovel.model.entity.pojo.novel.Book;
import com.lzw.breezeNovel.model.entity.query.PaginationResultQuery;
import com.lzw.breezeNovel.model.entity.query.Search;
import com.lzw.breezeNovel.model.entity.query.SimplePage;
import com.lzw.breezeNovel.model.enums.novel.BookStatus;
import jakarta.annotation.Resource;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 书籍服务控制类
 */
@Service
@SuppressWarnings("all")
public class BookServiceImpl implements BookService {

    /**
     * 注入mapper
     */
    @Resource
    private BookMapper bookMapper;
    /**
     * 注入章节表
     */
    @Resource
    private ChapterMapper chapterMapper;

    // 使用ThreadLocal确保日期格式化的线程安全
    private static final ThreadLocal<DateFormat> DATE_FORMATTER = ThreadLocal.withInitial(
            () -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    );


    /**
     * 新增小说
     * @param book
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addBook(@NotNull Book book) {
        //获取小说名称
        String bookName = book.getBookName();
        //判断小说名称是否存在
       Long count =  bookMapper.selectByBookName(bookName);
       if(count != 0)
       {
           throw new BaseException(500,"小说名称已存在");
       }
        Date date = new Date();
       //设置小说创建时间
       book.setCreateTime(date);
       //设置小说更新时间
       book.setUpdateTime(date);
       //设置小说的状态
       book.setStatus(BookStatus.SERIAL.getCode());
        bookMapper.addBook(book);
    }

    /**
     * 分页查询所有的书籍
     * @param book
     * @return
     */
    @Override
    public PaginationResultQuery<BookVo> pageBook(@NotNull Search book) {
        //对分页条件继续判断
        Integer page = Math.max(Optional.ofNullable(book.getPageNum()).orElse(1), 1);
        Integer size = Math.max(Optional.ofNullable(book.getPageSize()).orElse(10), 1);
        //查询书籍的数量
        int count = bookMapper.countBook(book);
        //判断是否有数据
        if(count == 0) {
            return new PaginationResultQuery<>(count, page, size, null);
        }
        //创建分页对象
        SimplePage simplePage = new SimplePage(count, page, size);
        //计算分页大小
       simplePage.action();
        //查询书籍
        List<Book> books = bookMapper.getBooksByTypeByPage(book.getKeyword(),simplePage.getStart(),size);
        //循环遍历
        List<BookVo> bookVos = books.stream().map(b -> {
            BookVo bookVo = new BookVo();
            //拷贝数据
            BeanUtils.copyProperties(b, bookVo);
            //获取小说的推荐状态
            Boolean isRecoomend = b.getRecomend() == 0 ? false : true;
            bookVo.setIsRecommend(isRecoomend);
            //获取小说的时间
            Date createTime = b.getCreateTime();
            //格式化时间
            String format = DATE_FORMATTER.get().format(createTime);
            bookVo.setCreateTime(format);
            //获取小说的状态
            Integer status = b.getStatus();
            String descByCode = BookStatus.getDescByCode(status);
            bookVo.setStatus(descByCode);
            return bookVo;
        }).collect(java.util.stream.Collectors.toList());
        return new PaginationResultQuery<>(count, page, size, bookVos);
    }

    /**
     * 删除小说
     * @param id
     */
    @Override
    public void deleteBook(Integer id) {
        bookMapper.deleteBook(id);
    }

    /**
     * 批量删除小说
     * @param ids
     */
    @Override
    public void deleteBooks(Long[] ids) {
        bookMapper.deleteBooks(ids);
    }

    /**
     * 更新小说
     * @param book
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBook(@NotNull Book book) {
        //获取小说名称
        String bookName = book.getBookName();
        //判断小说名称是否存在
        Long count =  bookMapper.selectByBookName(bookName);
        if(count != 0)
        {
            throw new BaseException(500,"小说名称已存在");
        }
        Date date = new Date();
        //设置小说更新时间
        book.setUpdateTime(date);
        //更新小说
        bookMapper.updateBook(book);
    }

    /**
     * 统计书籍
     * @return
     */
    @Override
    public StatisticsVo countBook() {
        return null;
    }
}
